package com.liu.cloud.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractNameValueGatewayFilterFactory;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.List;


@Slf4j
@Component
public class RequestHeaderHashGatewayFilterFactory extends AbstractNameValueGatewayFilterFactory {

    private DiscoveryClient discoveryClient;

    public RequestHeaderHashGatewayFilterFactory(DiscoveryClient discoveryClient) {
        this.discoveryClient = discoveryClient;
    }

    @Override
    public GatewayFilter apply(NameValueConfig config) {
        return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                // 获取请求路径
                URI uri = exchange.getRequest().getURI();
                String name = config.getName();
                String value = config.getValue();

                Route route = (Route) exchange.getAttributes().get(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
                String serviceName = route.getUri().getHost();
                if ("stock-server".equals(serviceName)) {
                    // 基于headerValue计算hash并选择实例
                    List<ServiceInstance> instances = discoveryClient.getInstances("stock-server");
                    ServiceInstance serviceInstance = instances.get(Math.abs(name.hashCode()) % instances.size());
                    log.info("hash: " + serviceInstance);
                }
                return chain.filter(exchange);
            }
        };
    }


}